<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.example.dao.UserDao" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="com.example.util.DBUtil" %>
<%@ page import="java.util.Optional" %>

<%
    request.setCharacterEncoding("UTF-8");
    // 获取用户ID参数
    String idParam = request.getParameter("id");
    
    if (idParam != null && !idParam.isEmpty()) {
        try {
            int userId = Integer.parseInt(idParam);
            
            try {
                UserDao userDao = new UserDao(DBUtil.getConnection());
                
                // 检查是否是POST请求（提交表单）
                if ("POST".equalsIgnoreCase(request.getMethod())) {
                    // 获取表单参数
                    String username = request.getParameter("username");
                    String realname = request.getParameter("realname");
                    String password = request.getParameter("password");
                    String email = request.getParameter("email");
                    String phone = request.getParameter("phone");
                    
                    // 验证必填字段
                    if (username == null || username.trim().isEmpty()) {
                        session.setAttribute("message", "用户名不能为空！");
                        session.setAttribute("messageType", "error");
                        response.sendRedirect("user_edit.jsp?id=" + userId);
                        return;
                    }
                    
                    // 获取用户信息
                    Optional<User> userOptional = userDao.getUserById(userId);
                    if (userOptional.isPresent()) {
                        User user = userOptional.get();
                        
                        // 更新用户对象
                        user.setUsername(username);
                        user.setRealname(realname);
                        // 只有当提供了新密码时才更新密码
                        if (password != null && !password.trim().isEmpty()) {
                            user.setPassword(password);
                        }
                        user.setEmail(email);
                        user.setPhone(phone);
                        
                        // 更新数据库中的用户信息
                        userDao.updateUser(user);
                        
                        // 设置成功消息并重定向
                        session.setAttribute("message", "用户信息更新成功！");
                        session.setAttribute("messageType", "success");
                        response.sendRedirect("user_info.jsp");
                        return;
                    } else {
                        // 用户不存在
                        session.setAttribute("message", "用户不存在！");
                        session.setAttribute("messageType", "error");
                        response.sendRedirect("user_info.jsp");
                        return;
                    }
                }
                
                // 获取用户信息用于显示表单
                Optional<User> userOptional = userDao.getUserById(userId);
                if (!userOptional.isPresent()) {
                    session.setAttribute("message", "用户不存在！");
                    session.setAttribute("messageType", "error");
                    response.sendRedirect("user_info.jsp");
                    return;
                }
                
                User user = userOptional.get();
%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>编辑用户信息</title>
    <%@ include file="header.jsp" %>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>编辑用户信息</h1>
        <a href="user_info.jsp" class="btn">返回用户列表</a>
    </div>
    
    <form action="user_edit.jsp?id=<%= userId %>" method="post">
        <input type="hidden" name="id" value="<%= user.getId() %>">
        
        <div class="form-group">
            <label for="username">用户名:</label>
            <input type="text" id="username" name="username" value="<%= user.getUsername() %>" required>
        </div>
        
        <div class="form-group">
            <label for="realname">真实姓名:</label>
            <input type="text" id="realname" name="realname" value="<%= user.getRealname() != null ? user.getRealname() : "" %>">
        </div>
        
        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" id="password" name="password" placeholder="留空表示不修改密码">
        </div>
        
        <div class="form-group">
            <label for="email">邮箱:</label>
            <input type="email" id="email" name="email" value="<%= user.getEmail() != null ? user.getEmail() : "" %>">
        </div>
        
        <div class="form-group">
            <label for="phone">电话:</label>
            <input type="text" id="phone" name="phone" value="<%= user.getPhone() != null ? user.getPhone() : "" %>">
        </div>
        
        <div class="form-group">
            <input type="submit" value="更新用户" class="btn btn-success">
            <input type="reset" value="重置" class="btn">
            <button type="button" class="btn" onclick="history.back()">取消</button>
        </div>
    </form>
</div>
</body>
</html>
<%
            } catch (Exception e) {
                e.printStackTrace();
                // 设置错误消息并重定向
                session.setAttribute("message", "系统错误: " + e.getMessage());
                session.setAttribute("messageType", "error");
                response.sendRedirect("user_info.jsp");
            }
        } catch (NumberFormatException e) {
            // ID格式错误
            session.setAttribute("message", "用户ID格式错误！");
            session.setAttribute("messageType", "error");
            response.sendRedirect("user_info.jsp");
        }
    } else {
        // 没有提供ID
        session.setAttribute("message", "未指定要编辑的用户！");
        session.setAttribute("messageType", "error");
        response.sendRedirect("user_info.jsp");
    }
%>